from elasticsearch import Elasticsearch
from datetime import datetime

ES = [
    "192.168.127.128:9200"
]
# 构建es操作对象
es = Elasticsearch(
    ES,
    # sniff before doing anything
    sniff_on_start=True,
    # refresh nodes after a node fails to respond
    sniff_on_connection_fail=True,
    # and also every 60 seconds
    sniffer_timeout=60
)

# 构建文档信息
doc = {
    'author': 'kimchy',
    'text': 'Elasticsearch: cool. bonsai cool.',
    'timestamp': datetime.now(),
}

docStr = {
    'author': 'xueXue',
    'text': 'xueGe 超级帅啊',
    'timestamp': datetime.now(),
}

# 构建查询语句
queryStr = {
    "query": {
        "match": {
            "author": "xueXue"
        }
    }
}


# 创建索引
def create_index(index, body=None):
    if es.indices.exists(index):
        return
    try:
        ret = es.index(index=index, body=body)
        print(ret)
    except Exception as e:
        print(e)


# 新增文档
def insertDoc(index, docStr):
    try:
        ret = es.index(index=index, body=docStr)
        print(ret)
    except Exception as e:
        print(e)


# 删除文档
def delDoc(index, docId):
    try:
        ret = es.delete(index=index, id=docId)
        print(ret)
    except Exception as e:
        print(e)


# 查询信息
def query(index, queryStr):
    result = []
    try:
        ret = es.search(queryStr, index=index)
        print("Got %d Hits:" % ret['hits']['total']['value'])
        for hit in ret['hits']['hits']:
            result.append(hit["_source"])
    except Exception as e:
        print(e)
    return result


print(query("t_author", queryStr))

# create_index('t_author', doc)
# insertDoc("t_author", docStr)
# delDoc("t_author",'A7j_fHUBsswDD4cFcyhr')
